package cn.melonlib.cores.commons.comp.service;

import cn.hutool.core.util.ReflectUtil;
import cn.melonlib.cores.commons.anno.ConfigBean;
import cn.melonlib.objects.maps.JsonMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SystemConfigReaderService extends ApplicationObjectSupport {


    public JsonMap<Object> getConfigInfo(){
        Map<String,Object> beans= this.getApplicationContext().getBeansWithAnnotation(ConfigBean.class);
        return beans.entrySet().stream().reduce(JsonMap.createMap(),(m,bean)->m.append(name(bean),config(bean)),(m,b)->null);
    }

    private String name(Map.Entry<String,Object> entry){
        ConfigBean configBean= AnnotationUtils.findAnnotation(AopUtils.getTargetClass(entry.getValue()),ConfigBean.class);
        if(StringUtils.isNotBlank(configBean.name())){
            return configBean.name();
        }else{
            return entry.getKey();
        }
    }

    private Object config(Map.Entry<String,Object> entry){
        ConfigBean configBean= AnnotationUtils.findAnnotation(AopUtils.getTargetClass(entry.getValue()),ConfigBean.class);
        return ReflectUtil.invoke(entry.getValue(),configBean.method());
    }
}
